<?php
/***************
* @Project	Warabi
* @Author	Feifei
* @Date		04/10/2009
***************/

/**This module is to deal the ap login**/

include_once($_SERVER['DOCUMENT_ROOT'].'/header.inc.php');

$httprequest = new wbHttpRequest();

list($headers , $body) = $httprequest->output();

/** a simple way to deal the simple request **/
$xmlparser = simplexml_load_string($body);
if(!$xmlparser){
	header(error_xml_structure);
	exit;
}
$usr = strval($xmlparser->usr);  //get the app username
$lang = strval($xmlparser->lang);  //get the app language

/** if the username is empty **/
if(empty($usr)){
	header(error_xml_element_missing);
	exit;
}

$usr = filterValue($usr);
$lang = filterValue($lang);

/***insert the user into database 
***or get the passcode from database
**/
$db = new wbDatabase();
$sql = "select * from ".__table_app_user__." where username='".$usr."'";
$set = $db->query($sql);
$passcode = "";

if($db->countResult($set) !=0){
	$tempset = $db->fetchResultBySet($set,MYSQLI_ASSOC);
	$passcode = $tempset["password"];
	$sql = "update ".__table_app_user__." set lastlogin=now() where username='".$usr."'";
	$err = $db->query($sql);
}else{
	/**generate the passcode**/
	$ghd = new Guid();
	$passcode = $ghd->rawOutput();
	$sql = "insert into ".__table_app_user__."
				set username = '".$usr."' ,
					  language = '".$lang."',
					  password = '".$passcode."',
					  lastlogin = now()";
	$err = $db->query($sql);
}

$db->freeResult($set);
$db->disconnect();

if(!$err){
	header(error_server_system);
	exit;
}

/***put the response to the client**/
$tid = getTid();
$resBody = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
$resBody .= "<entry>";
$resBody .= "<pwd>".$passcode."</pwd>";
$resBody .= "<tid>".$tid."</tid>";
$resBody .= "</entry>";

header(success_response);
header('Content-Type: text/xml');
header('Content-Length: '.strlen($resBody));
echo $resBody;

?>